//
//  QrCodeController.m
//  gdemm
//
//  Created by 乔明超 on 16/5/9.
//  Copyright © 2016年 Goldencis. All rights reserved.
//

#import "QrCodeController.h"
#import "AppDelegate.h"
#import "FlashLight.h"
#import "HeadView.h"
#import "LocationPolicyManager.h"
@interface QrCodeController ()
{
    UIImageView *imageView;
}
@property (nonatomic,copy) NSString *information;
@property (strong,nonatomic) UIButton *mBtnLeft;
@property (strong,nonatomic) UIButton *mBtnright;
@property (strong,nonatomic) UILabel *mlabel;
@end

@implementation QrCodeController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    imageView = [[UIImageView alloc]init];
    imageView.image = [[Utils getImageByDevce:@"qrcode_scan_frame"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    [imageView sizeToFit];
    imageView.center = self.view.center;
    [self.view addSubview:imageView];
    upOrdown = NO;
    num = 0;
     _line = [[UIImageView alloc]init];
    [_line sizeToFit];
    _line.centerX = imageView.centerX;
    _line.top = CGRectGetMinY(imageView.frame)+10;
    _line.image = [Utils getImageByDevce:@"qrcode_scan_line"];
    [self.view addSubview:self.line];
    timer = [NSTimer timerWithTimeInterval:0.02 target:self selector:@selector(animation1) userInfo:nil repeats:YES];
    // 添加到运行循环
    [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
    
}
-(void)viewWillAppear:(BOOL)animated
{
    [self setupCamera];
}

-(void)animation1
{
    
    if (upOrdown == NO) {
        num ++;
        _line.frame = CGRectMake(CGRectGetMinX(imageView.frame)+10, CGRectGetMinY(imageView.frame)+10+2*num, imageView.width - 20, 5);
        
        if (num ==(int)(( imageView.width - 20)/2)) {
            upOrdown = YES;
        }
    }
    else {
        num --;
        _line.frame =CGRectMake(CGRectGetMinX(imageView.frame)+10, CGRectGetMinY(imageView.frame)+10+2*num, imageView.width-20,5);
        
        if (num == 0) {
            upOrdown = NO;
        }
    }
    
}

- (void)setupCamera{
    // Device
    _device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    
    // Input
    _input = [AVCaptureDeviceInput deviceInputWithDevice:self.device error:nil];
    
    // Output
    _output = [[AVCaptureMetadataOutput alloc]init];
    [_output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
    
    _output.rectOfInterest = CGRectMake(0.2, 0.2, 0.6, 0.6);
    _session = [[AVCaptureSession alloc]init];
    [_session setSessionPreset:AVCaptureSessionPresetHigh];
    if ([_session canAddInput:self.input])
    {
        [_session addInput:self.input];
    }
    
    if ([_session canAddOutput:self.output])
    {
        [_session addOutput:self.output];
    }
    
    // 条码类型 AVMetadataObjectTypeQRCode
    _output.metadataObjectTypes =@[AVMetadataObjectTypeEAN13Code, AVMetadataObjectTypeEAN8Code, AVMetadataObjectTypeCode128Code, AVMetadataObjectTypeQRCode];
    
    // Preview
    _preview =[AVCaptureVideoPreviewLayer layerWithSession:self.session];
    _preview.videoGravity = AVLayerVideoGravityResize;
    _preview.frame =self.view.bounds;
    [self.view.layer insertSublayer:self.preview atIndex:0];
    
    [self.view bringSubviewToFront:imageView];
    
    [self setOverView];
    
    // Start
    [_session startRunning];
    
}


- (CGRect)rectOfInterestByScanViewRect:(CGRect)rect {
    CGFloat width = CGRectGetWidth(self.view.frame);
    CGFloat height = CGRectGetHeight(self.view.frame);
    CGFloat x = CGRectGetMinX(rect) / width;
    CGFloat y = CGRectGetMinY(rect) / height;
    
    CGFloat w = CGRectGetWidth(rect) / width;
    CGFloat h = CGRectGetHeight(rect) / height;
    return CGRectMake(x, y, w, h);
}

#pragma mark - 添加模糊效果
- (void)setOverView {
    CGFloat width = CGRectGetWidth(self.view.frame);
    CGFloat height = CGRectGetHeight(self.view.frame);
    
    CGFloat x = CGRectGetMinX(imageView.frame);
    CGFloat y = CGRectGetMinY(imageView.frame);
    CGFloat w = CGRectGetWidth(imageView.frame);
    CGFloat h = CGRectGetHeight(imageView.frame);
    
    [self creatView:CGRectMake(0, 0, width, y)];
    [self creatView:CGRectMake(0, y, x, h)];
    [self creatView:CGRectMake(0, y + h, width, height - y - h)];
    [self creatView:CGRectMake(x + w, y, width - x - w, h)];
    HeadView *mheadView = [[HeadView alloc]init];
    [mheadView.mBtnLeft setImage:[Utils getImageByDevce:@"navigationBar_back"] forState:UIControlStateNormal];
    [mheadView.mBtnLeft addTarget:self action:@selector(popViewControllerHandler) forControlEvents:UIControlEventTouchUpInside];
    mheadView.mTitle.text = @"扫码";

    [mheadView.mBtnRight setImage:[UIImage imageNamed:@"scan_light"] forState:UIControlStateNormal];
    [mheadView.mBtnRight addTarget:self action:@selector(onOffLight:) forControlEvents:UIControlEventTouchUpInside];
    [mheadView showRightBtn:YES];
    mheadView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:mheadView];
    
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, CGRectGetMinY(imageView.frame)- 60, WINDOWWIDTH, 40*KHeightScale)];
    label.text = NSLocalizedString(@"str_scanInQRCodeBox", @"对准二维码到框内即可扫描");
    label.font = [UIFont systemFontOfSize:13];
    label.textAlignment = NSTextAlignmentCenter;
    label.textColor = [UIColor whiteColor];
    [self.view addSubview:label];

}

- (void)creatView:(CGRect)rect {
    CGFloat alpha = 0.5;
    UIColor *backColor = [UIColor blackColor];//[UIColor grayColor];
    UIView *view = [[UIView alloc] initWithFrame:rect];
    view.backgroundColor = backColor;
    view.alpha = alpha;
    [self.view addSubview:view];
}

#pragma mark AVCaptureMetadataOutputObjectsDelegate
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection
{
    NSString *stringValue;
    
    if ([metadataObjects count] >0)
    {
        AVMetadataMachineReadableCodeObject * metadataObject = [metadataObjects objectAtIndex:0];
        /**
         *  获取扫描结果
         */
        stringValue = metadataObject.stringValue;
    }
    HRLog(@"二维码扫描结果:%@",[NSString stringWithFormat:@"扫描结果：%@", stringValue]);
    [LocationPolicyManager getInstance].mQrcode = stringValue;
    
    [self popViewControllerHandler];
    [_session stopRunning];
    [timer invalidate];
    
    
    
    
}

- (void)popViewControllerHandler{
    [self.navigationController popViewControllerAnimated:YES];
    [FlashLight getInstance].onOffFlag = NO;
}

- (void)onOffLight:(UIButton *)sender{
    sender.selected = !sender.selected;
    [FlashLight getInstance].onOffFlag = sender.selected;
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
